php 地址重写,使用PHP重写URL |
您所在的位置:网站首页 › php url重写 › php 地址重写,使用PHP重写URL |
如果您只想更改路由,picture.php那么添加重写规则.htaccess将满足您的需求,但是,如果您希望在Wordpress中重写URL,那么PHP就是这样。这是一个简单的例子。 文件夹结构 但是也有一些需要在根文件夹中的两个文件,.htaccess并且index.php,这将是很好的放置的其余部分.php在不同的文件夹中的文件一样inc/。 root/ inc/ .htaccess index.php 的.htaccess RewriteEngine On RewriteRule ^inc/.*$ index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php [QSA,L] 该文件有四个指令: RewriteEngine - 启用重写引擎 RewriteRule- 拒绝访问文件inc/夹中的所有文件,将对该文件夹的任何调用重定向到index.php RewriteCond - 允许直接访问所有其他文件(如图像,CSS或脚本) RewriteRule - 重定向任何其他内容 index.php 的index.php 因为现在所有内容都被重定向到index.php,所以将确定url是否正确,所有参数是否存在以及参数类型是否正确。 要测试网址,我们需要有一套规则,最好的工具是正则表达式。通过使用正则表达式,我们将一击就杀死两只苍蝇。要通过此测试的Url必须具有在允许的字符上测试的所有必需参数。以下是一些规则示例。 $rules = array( 'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51' 'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug' 'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug' 'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact' 'post' => "/(?'post'[\w\-]+)", // '/post-slug' 'home' => "/" // '/' ); 接下来是准备请求uri。 $uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' ); $uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' ); $uri = urldecode( $uri ); 现在我们有了uri请求,最后一步是测试uri的正则表达式规则。 foreach ( $rules as $action => $rule ) { if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) { /* now you know the action and parameters so you can * include appropriate template file ( or proceed in some other way ) */ } } 由于我们在正则表达式中使用命名子模式,因此填充$params数组几乎与PHP填充$_GET数组相同。但是,在使用动态URL时,$_GET将填充数组而不检查任何参数。 /图片/一些+文本/ 51 排列 ( [0] => / picture / some text / 51 [text] =>一些文字 [1] =>一些文字 [id] => 51 [2] => 51 ) picture.php?文本=一些文字+&ID = 51 排列 ( [text] =>一些文字 [id] => 51 ) 这几行代码和正则表达式的基本知识足以开始构建一个可靠的路由系统。 完整的来源 define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' ); $rules = array( 'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51' 'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug' 'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug' 'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact' 'post' => "/(?'post'[\w\-]+)", // '/post-slug' 'home' => "/" // '/' ); $uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' ); $uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' ); $uri = urldecode( $uri ); foreach ( $rules as $action => $rule ) { if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) { /* now you know the action and parameters so you can * include appropriate template file ( or proceed in some other way ) */ include( INCLUDE_DIR . $action . '.php' ); // exit to avoid the 404 message exit(); } } // nothing is found so handle the 404 error include( INCLUDE_DIR . '404.php' ); |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |